<template>
  <div>
    <el-steps class="dataSourceStep" :active="active" align-center>
      <el-step title="选择数据源" />
      <!-- <el-step title="版本选择" /> -->
      <el-step title="信息配置" />
    </el-steps>
    <!-- <el-input v-if='active == 1' v-model='searchValue' placeholder='按数据源名称搜索' class='type'></el-input> -->
    <el-container class="container-add-box">
      <!-- <el-aside v-if='active == 1' width="200px" style='padding: 0'>
        <ul class='list'>
          <li v-for='datasource in datasourceList' :class='{"li-select": datasource.name === currentDatasource}' @click='() => {handleClickDatasource(datasource)}'>
            {{datasource.name}}
          </li>
        </ul>
      </el-aside> -->
      <el-main>
        <el-row v-if="active == 1">
          <el-col
            :span="8"
            @click="
              () => {
                handleClickImg(database.name)
              }
            "
            class="col"
            v-for="database in databaseTypeList"
          >
            <div class="img-logo">
              <img :src="database.imgSrc" alt="" />
            </div>
            <span class="img-logo-name">{{ database.name }}</span>
          </el-col>
        </el-row>
        <div v-if="active == 2">
          <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" style="margin-top: 40px">
            <el-form-item label="数据源类型" prop="type">
              <el-input v-model="form.type" placeholder="请输入数据源类型" disabled></el-input>
            </el-form-item>
            <el-form-item v-if="showItem('datasourceName')" label="数据源名称" prop="datasourceName">
              <el-input v-model="form.datasourceName" placeholder="请输入数据源名称"></el-input>
            </el-form-item>
            <el-form-item v-if="showItem('description')" label="描述">
              <el-input v-model="form.description" type="textarea" :rows="6" placeholder="请输入描述"></el-input>
            </el-form-item>
            <el-form-item v-if="showItem('linkWay')" label="连接方式">
              <el-radio-group v-model="form.linkWay" type="textarea" :rows="6" placeholder="请输入描述">
                <el-radio :label="0">集群地址</el-radio>
                <el-radio :label="1">Broker地址</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              v-if="showItem('groupAddress') && (form.linkWay === 0 || form.type.toLowerCase() === 'mongodb')"
              label="集群地址"
              prop="groupAddress"
            >
              <el-input
                v-model="form.groupAddress"
                type="textarea"
                :rows="6"
                :placeholder="getGroupAddressPlaceholder()"
              ></el-input>
            </el-form-item>
            <el-form-item
              v-if="showItem('BrokerAddress') && form.linkWay === 1"
              label="Broker地址"
              prop="BrokerAddress"
            >
              <el-input
                v-model="form.BrokerAddress"
                type="textarea"
                :rows="6"
                placeholder="Broker地址，例如IP1:Port,IP2:Port,IP3:Port/子目录"
              ></el-input>
            </el-form-item>
            <el-form-item v-if="showItem('groupName')" label="集群名称">
              <el-input v-model="form.groupName" placeholder="请输入集群名称"></el-input>
            </el-form-item>
            <el-form-item v-if="showItem('JDBC URL')" label="JDBC URL" prop="url">
              <el-input v-model="form.url" placeholder="请输入JDBC URL(MongoDB格式为IP:PORT)"></el-input>
            </el-form-item>
            <el-form-item v-if="showItem('authenticationMethod')" label="认证方式" prop="authenticationMethod">
              <el-select v-model="form.authenticationMethod" placeholder="请选择认证方式">
                <el-option :value="0" label="SASL_PLAINTEXT"></el-option>
                <el-option :value="1" label="kerberos"></el-option>
                <el-option :value="2" label="无"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              v-if="
                showItem('username') &&
                (form.type.toLowerCase() !== 'kafka' ||
                  (form.type.toLowerCase() === 'kafka' && form.authenticationMethod === 0))
              "
              label="用户名"
              prop="username"
            >
              <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
            </el-form-item>
            <el-form-item
              v-if="
                showItem('password') &&
                (form.type.toLowerCase() !== 'kafka' ||
                  (form.type.toLowerCase() === 'kafka' && form.authenticationMethod === 0))
              "
              label="密码"
              prop="password"
            >
              <el-input v-model="form.password" show-password placeholder="请输入密码"></el-input>
            </el-form-item>
            <el-form-item v-if="showItem('kerberosFile') && form.authenticationMethod === 1" prop="password">
              <el-upload accept=".zip" class="upload-demo" :http-request="handleUpload" :show-file-list="false">
                <el-button type="primary">上传文件</el-button>
                <div>仅支持Zip格式，压缩包需包含xxx.keytab、krb5.config文件。上传文件前，请在控制台开启SFTP服务。</div>
                <div>上传单个文件，支持扩展格式：.zip</div>
              </el-upload>
            </el-form-item>
            <el-form-item v-if="showItem('database')" label="数据库" prop="database">
              <el-input v-model="form.database" placeholder="请输入数据库"></el-input>
            </el-form-item>
            <!-- <el-form-item label="级别" prop="identifier">
              <el-radio-group v-model="form.identifier" @change="handleChangeIdentifier">
                <el-radio :label="1">省</el-radio>
                <el-radio :label="2">市</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="form.identifier === 2" label="16市" prop="identifier">
              <el-select v-model="form.cityName" @change="handleChangeCity">
                <el-option
                  v-for="city in cityListWithoutAll"
                  :label="city.cityName"
                  :value="city.cityName"
                  :key="city"
                ></el-option>
              </el-select>
            </el-form-item> -->
            <!-- <el-form-item v-if="showItem('datasourceType')" label="数据源类型" prop="identifier">
              <el-select v-model="form.dataSourceType">
                <el-option
                  v-for="item in datasourceType"
                  :label="item.label"
                  :value="item.value"
                  :key="item"
                ></el-option>
              </el-select>
            </el-form-item> -->
            <!-- <el-form-item label="分类" prop="baseType">
              <el-radio-group v-model="form.baseType">
                <el-radio v-for="item in dictionaryStore.databaseType" :label="item.value" :key="item">
                  {{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item> -->
            <el-form-item v-if="showItem('qualityResultType')" label="质控类型" prop="qualityResultType">
              <el-input v-model="form.qualityResultType" placeholder="请输入分类" clearable />
            </el-form-item>

            <!-- <el-form-item label-width="300" label="是否为源头数据源" prop="isSource">
              <el-radio-group v-model="form.isSource">
                <el-radio
                  v-for="item in [
                    { label: '是', value: '1' },
                    { label: '否', value: '0' }
                  ]"
                  :label="item.value"
                  :key="item"
                >
                  {{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item> -->

            <!-- <el-form-item v-if="form.isSource == '0'" label-width="300" label="父级数据源" prop="isSource">
              <el-transfer
                v-model="form.sourceList"
                filterable
                :filter-method="filterMethod"
                filter-placeholder="搜索"
                :data="allDataSourceList"
                :titles="['全部数据源', '已选择']"
                :props="{
                  key: '_id'
                }"
              >
                <template #default="{ option }">
                  <span>{{ option.datasourceName }} - {{ option.type }}</span>
                </template>
              </el-transfer>
            </el-form-item> -->
            <el-form-item label="数据权限">
              <el-radio-group v-model="form.openLevel">
                <el-radio label="1">私人</el-radio>
                <el-radio label="2">本角色</el-radio>
                <el-radio label="3">公开</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </div>
      </el-main>
    </el-container>
    <div v-show="active == 2" style="text-align: center; padding: 10px; border-top: 0">
      <el-button type="primary" @click="handleTestLink" :loading="testLoading">测试连通性</el-button>
      <el-button type="primary" plain @click="active = 1">上一步</el-button>
      <el-button type="primary" @click="handleOk" :loading="addLoading">确定</el-button>
    </div>
  </div>
</template>

<script setup>
import { remoteAdd, remoteTest, getDatabaseList } from '@/api/datasourceCenter'
import { ElMessage } from 'element-plus'
import _cloneDeep from 'lodash/cloneDeep'
import MySQLPng from '@/assets/image/MySQL.png'
import OraclePng from '@/assets/image/Oracle.png'
import ElasticSearchPng from '@/assets/image/ElasticSearch.png'
import MongoDBPng from '@/assets/database/MongoDB.png'
import KafkaPng from '@/assets/database/Kafka.png'
import ClickHousePng from '@/assets/image/ClickHouse.png'
import SQLServerPng from '@/assets/image/SQLServer.png'
import DaMeng from '@/assets/image/DaMeng.png'
import PostgreSQLPNG from '@/assets/image/PostgreSQL.png'
import DuckDB from '@/assets/image/DuckDB.png'
import starrocks from '@/assets/image/starrocks.png'
import doris from '@/assets/image/doris.png'
// import { cityListWithoutAll } from '@/utils/city.js'
import { getDictType } from '@/api/system/dictionary'
// import { useDictionaryStore } from '@/store/modules/dictionary'

import GBase from '@/assets/database/GBase.jpeg'
import GreatDB from '@/assets/database/GreatDB.png'
import Highgo from '@/assets/database/Highgo.jpeg'
import KingbaseES from '@/assets/database/KingbaseES.jpeg'
import PolarDB from '@/assets/database/PolarDB.png'
import SeaboxSQL from '@/assets/database/SeaboxSQL.jpeg'
import TdSQL from '@/assets/database/TdSQL.png'
import UxDB from '@/assets/database/UxDB.jpeg'
import VastBase from '@/assets/database/VastBase.png'
import XuguDB from '@/assets/database/XuguDB.png'

import { sm4Encrypt } from '@/utils/sm4'

// const dictionaryStore = useDictionaryStore()
const emits = defineEmits(['refresh'])
const formRef = ref()
const form = ref({
  username: '',
  password: '',
  type: '',
  datasourceName: '',
  description: '',
  url: '',
  groupAddress: '',
  BrokerAddress: '',
  database: '',
  groupName: '',
  linkWay: 0,
  authenticationMethod: 2,
  identifier: 1,
  baseType: '3',
  cityName: '山东省',
  cityCode: '370000',
  dataSourceType: '',
  qualityResultType: '',
  isSource: '0',
  openLevel: '1'
})
const rules = {
  type: [{ required: true, message: '请填写数据源类型', trigger: 'blur' }],
  datasourceName: [{ required: true, message: '请填写数据源名称', trigger: 'blur' }],
  url: [{ required: true, message: '请填写JDBC URL', trigger: 'blur' }],
  groupAddress: [{ required: true, message: '请填写集群地址', trigger: 'blur' }],
  database: [{ required: true, message: '请填写数据库', trigger: 'blur' }],
  linkWay: [{ required: true, message: '请选择连接方式', trigger: 'trigger' }]
}
const active = ref(1)
const searchValue = ref('')
const datasourceList = ref([
  { name: '全部' },
  { name: '常用' },
  { name: '国产化' },
  { name: '大数据存储' },
  { name: 'MPP' },
  { name: '半结构化' },
  { name: '分析型' },
  { name: 'NoSQL' },
  { name: '实时' },
  { name: '时序' },
  { name: '接口' }
])

const allDataSourceList = ref([])

const databaseTypeList = ref([
  {
    imgSrc: MySQLPng,
    name: 'MySQL'
  },
  {
    imgSrc: OraclePng,
    name: 'Oracle'
  },
  {
    imgSrc: ElasticSearchPng,
    name: 'ElasticSearch'
  },
  {
    imgSrc: MongoDBPng,
    name: 'MongoDB'
  },
  // {
  //   imgSrc: KafkaPng,
  //   name: "Kafka",
  // },
  {
    imgSrc: ClickHousePng,
    name: 'ClickHouse'
  },
  {
    imgSrc: SQLServerPng,
    name: 'SQLServer'
  },
  {
    imgSrc: DaMeng,
    name: 'DaMeng'
  },
  {
    imgSrc: PostgreSQLPNG,
    name: 'postGreSql'
  },
  {
    imgSrc: DuckDB,
    name: 'DuckDB'
  },
  {
    imgSrc: GBase,
    name: 'GBase'
  },
  {
    imgSrc: GreatDB,
    name: 'GreatDB'
  },
  {
    imgSrc: Highgo,
    name: 'Highgo'
  },
  {
    imgSrc: KingbaseES,
    name: 'KingbaseES'
  },
  {
    imgSrc: PolarDB,
    name: 'PolarDB'
  },
  {
    imgSrc: SeaboxSQL,
    name: 'SeaboxSQL'
  },
  {
    imgSrc: TdSQL,
    name: 'TdSQL'
  },
  {
    imgSrc: UxDB,
    name: 'UxDB'
  },
  {
    imgSrc: VastBase,
    name: 'VastBase'
  },
  {
    imgSrc: XuguDB,
    name: 'XuguDB'
  },
  {
    imgSrc: starrocks,
    name: 'Starrocks'
  },
  {
    imgSrc: doris,
    name: 'Doris'
  }
])

const getDatabaseListData = async () => {
  const res = await getDatabaseList()
  console.log('res')
  console.log(res)

  allDataSourceList.value = res.data
}

getDatabaseListData()

const filterMethod = (query, item) => {
  return item.datasourceName.includes(query.toLowerCase())
}

const handleChangeIdentifier = function () {
  if (form.value.identifier === 1) {
    form.value.cityName = '山东省'
    form.value.cityCode = '370000'
  }
  if (form.value.identifier === 2) {
    form.value.cityName = '济南市'
    form.value.cityCode = '370100'
  }
}
const handleChangeCity = function (a) {
  form.value.cityCode = cityListWithoutAll.find((item) => item.cityName === a)?.cityCode || ''
  console.log(form.value)
}
const showItem = function (itemName) {
  console.log(itemName)
  switch (form.value.type.toLowerCase()) {
    case 'oracle':
    case 'mysql':
    case 'gbase':
    case 'greatdb':
    case 'highgo':
    case 'kingbasees':
    case 'polardb':
    case 'seaboxsql':
    case 'tdsql':
    case 'uxdb':
    case 'vastbase':
    case 'xugudb':
    case 'starrocks':
    case 'doris':
      return ['datasourceName', 'description', 'JDBC URL', 'username', 'password'].includes(itemName)
      break
    case 'elasticsearch':
      return ['datasourceName', 'description', 'groupAddress', 'groupName', 'username', 'password'].includes(itemName)
      break
    case 'mongodb':
      return [
        'datasourceName',
        'description',
        'JDBC URL',
        'username',
        'password',
        'database',
        'datasourceType'
      ].includes(itemName)
      break
    case 'kafka':
      return [
        'datasourceName',
        'description',
        'linkWay',
        'groupAddress',
        'BrokerAddress',
        'authenticationMethod',
        'username',
        'password',
        'kerberosFile'
      ].includes(itemName)
      break
    case 'clickhouse':
      return ['datasourceName', 'description', 'JDBC URL', 'username', 'password', 'qualityResultType'].includes(
        itemName
      )
      break
    case 'sqlserver':
      return ['datasourceName', 'description', 'JDBC URL', 'username', 'password'].includes(itemName)
      break
    case 'dameng':
      return ['datasourceName', 'description', 'JDBC URL', 'username', 'password'].includes(itemName)
      break
    case 'postgresql':
      return ['datasourceName', 'description', 'JDBC URL', 'username', 'password'].includes(itemName)
      break
    case 'duckdb':
      return ['datasourceName', 'description', 'JDBC URL', 'username', 'password'].includes(itemName)
      break
    default:
      return true
      break
  }
}
// 设置不同数据库类型此选项placeholder
const getGroupAddressPlaceholder = () => {
  if (form.value.type.toLowerCase() === 'kafka') {
    return '集群地址，单个节点地址采用host:port形式，多个节点的地址用逗号连接'
  }
  if (form.value.type.toLowerCase() === 'mongodb') {
    return 'MongoDB集群地址，例如：IP1:Port,IP2:Port,IP3:Port'
  }
}
// 点击数据库图片进入表单
const handleClickImg = function (database = 'MySQL') {
  active.value = 2
  form.value.type = database
}
const currentDatasource = ref('') // 当前数据库
// 数据库被点击
const handleClickDatasource = (datasource) => {
  currentDatasource.value = datasource.name
}
const testLoading = ref(false) // 测试连通性loading
// 测试连通性
const handleTestLink = function () {
  formRef.value
    .validate()
    .then(() => {
      testLoading.value = true
      const temp = _cloneDeep(form.value)
      if (['elasticsearch'].includes(form.value.type.toLowerCase())) {
        temp.groupAddress = temp.groupAddress.split(',')
      }
      temp.password = sm4Encrypt(temp.password)
      remoteTest(temp)
        .then((res) => {
          ElMessage.success(res.msg)
        })
        .finally(() => {
          testLoading.value = false
        })
    })
    .catch(() => {
      ElMessage.error('请填写必填项')
      addLoading.value = false
    })
}
const addLoading = ref(false) // 添加btn loading
const handleOk = function () {
  // 添加

  //打印未填写的必填项
  console.log(formRef.value)
  console.log(formRef.value.validate())

  formRef.value
    .validate()
    .then(() => {
      addLoading.value = true
      const temp = _cloneDeep(form.value)
      if (['elasticsearch'].includes(form.value.type.toLowerCase())) {
        temp.groupAddress = temp.groupAddress.split(',')
      }

      let params = {
        ...temp,
        password: sm4Encrypt(temp.password)
      }
      remoteAdd(params)
        .then((res) => {
          ElMessage.success(res.msg)
          emits('refresh')
        })
        .finally(() => {
          addLoading.value = false
        })
    })
    .catch((err) => {
      console.log(err)
      ElMessage.error('请填写必填项')
      addLoading.value = false
    })
}
watch(
  () => active.value,
  () => {
    form.value.username = ''
    form.value.password = ''
    form.value.datasourceName = ''
    form.value.description = ''
    form.value.url = ''
    form.value.groupAddress = ''
    form.value.BrokerAddress = ''
    form.value.database = ''
    form.value.linkWay = 0
    form.value.groupName = ''
    form.value.authenticationMethod = 2
    form.value.cityName = '山东省'
    form.value.cityCode = '370000'
    form.value.dataSourceType = ''
    form.value.qualityResultType = ''
    form.value.openLevel = '1'
  }
)

watch(
  () => form.value.identifier,
  (val) => {
    if (val === 1) {
      form.value.cityName = '山东省'
      form.value.cityCode = '370000'
    }
    if (val === 2) {
      form.value.cityName = '济南市'
      form.value.cityCode = '370100'
    }
  },
  {
    immediate: true
  }
)
const datasourceType = ref([])
onMounted(() => {
  // 获取分类字典
  // getDictType('dataSourceType').then((res) => {
  //   datasourceType.value.length = 0
  //   datasourceType.value = res.data.map((item) => ({
  //     label: item.dictLabel,
  //     value: item.dictValue
  //   }))
  // })
  // dictionaryStore.getDatabaseType()
})
</script>

<style lang="scss" scoped>
@import '../style/addDatasource.scss';
.el-transfer {
  width: 100%;
}
:deep(.el-transfer-panel) {
  width: 38%;
}
.dataSourceStep {
  :deep(.el-step__icon) {
    width: 40px;
    height: 40px;
    .el-step__icon-inner {
      font-family: PingFangSC, PingFang SC;
      font-weight: 500;
      font-size: 19px;
      color: #1e5aff;
      line-height: 26px;
      text-align: left;
      font-style: normal;
    }
  }
  :deep(.el-step__line) {
    border-top: 2px dashed #ccd1de;
    height: 0;
    background-color: transparent;
    top: 18px;
  }
  :deep(.is-finish) {
    .el-step__line-inner {
      margin-top: -2px;
    }
  }
}
</style>
